package com.weixun.utils.record;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import org.apache.commons.beanutils.ConvertUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Map;

public class RecordUtils {
    private static final Logger logger = LoggerFactory.getLogger(RecordUtils.class);

    /**
     * Model 转 Record
     * @param
     * @return
     */
    public static Record converRecord(Model<?> model) {
        Record      r =new Record();
        r.setColumns(model);
        return r;
    }


    /**
     * Record 转 任意实例类
     * @param
     * @param record
     * @return
     */
    public static <T> T converModel(Class<T> clazz,Record record){

        try {
            return	  convertMap(clazz, record.getColumns());
        } catch (Exception e) {
            logger.error("Record 转 T 异常... ",e);
        }

        return null;
    }


    public static <T> T convertMap(Class<T> type, Map<String, Object> map) throws Exception {
        T  obj = type.newInstance();

        // 获取类属性
        BeanInfo beanInfo = Introspector.getBeanInfo(type);

        // 给 JavaBean 对象的属性赋值
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();

            if (map.containsKey(propertyName)) {
                String value = ConvertUtils.convert(map.get(propertyName));
                Object[] args = new Object[1];
                args[0] = ConvertUtils.convert(value, descriptor.getPropertyType());

                descriptor.getWriteMethod().invoke(obj, args);

            }
        }
        return obj;
    }

    public static void main(String[] args) {
        //Model
//        Friend friend = new Friend();
//        friend.setID(111L);
//        friend.setIMAGES("image");
//        friend.setMSG("msgsss");


//        Record r  = 	converRecord(friend);
//        System.out.println(r.getStr("IMAGES"));
//
//        Friend friendsss =converModel(Friend.class, r);
//        System.out.println(friendsss.getID());
    }
}
